import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jd_flutter/base/foundation/jd_colors.dart';
import 'package:jd_flutter/base/widget/basic/base_gesture.dart';
import 'package:jd_flutter/base/widget/image/jd_asset_image.dart';
import 'package:jd_flutter/base/widget/image/jd_network_image.dart';

/// 登录模块的输入框封装
class LoginTextField extends StatefulWidget {
  const LoginTextField({
    super.key,
    required this.controller,
    this.maxLength = 11,
    this.autoFocus = false,
    this.keyboardType = TextInputType.text,
    this.hintText = '',
    this.focusNode,
    this.phoneNoOk = false,
    this.getVCode,
    this.keyName,
  });

  final bool phoneNoOk;
  final TextEditingController controller;
  final int maxLength;
  final bool autoFocus;
  final TextInputType keyboardType;
  final String hintText;
  final FocusNode? focusNode;
  final Future<bool> Function()? getVCode;

  /// 用于集成测试寻找widget
  final String? keyName;

  @override
  State<LoginTextField> createState() => _LoginTextFieldState();
}

class _LoginTextFieldState extends State<LoginTextField> {
  bool _isShowDelete = false;
  bool _clickable = false;

  /// 倒计时秒数
  final int _second = 10;

  /// 当前秒数
  late final int _currentSecond = 0;
  bool isClicked = false;
  StreamSubscription<dynamic>? _subscription;

  @override
  void initState() {
    /// 获取初始化值
    _isShowDelete = widget.controller.text.isNotEmpty;
    _clickable = widget.phoneNoOk;

    /// 监听输入改变
    widget.controller.addListener(isEmpty);
    super.initState();
  }

  void isEmpty() {
    final bool isNotEmpty = widget.controller.text.isNotEmpty;

    /// 状态不一样在刷新，避免重复不必要的setState
    if (isNotEmpty != _isShowDelete) {
      setState(() {
        _isShowDelete = isNotEmpty;
      });
    }
  }

  @override
  void dispose() {
    _subscription?.cancel();
    widget.controller.removeListener(isEmpty);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget textField = TextField(
      focusNode: widget.focusNode,
      maxLength: widget.maxLength,
      autofocus: widget.autoFocus,
      controller: widget.controller,
      textAlignVertical: TextAlignVertical.center,
      cursorColor: const Color(0xFFF6C113),
      maxLines: 1,
      cursorWidth: 1,
      textInputAction: TextInputAction.done,
      keyboardType: widget.keyboardType,
      // 数字、手机号限制格式为0到9， 密码限制不包含汉字
      inputFormatters: (widget.keyboardType == TextInputType.number ||
              widget.keyboardType == TextInputType.phone)
          ? [FilteringTextInputFormatter.allow(RegExp('[0-9]'))]
          : [FilteringTextInputFormatter.deny(RegExp('[\u4e00-\u9fa5]'))],
      decoration: InputDecoration(
        filled: true,
        fillColor: JDColors.cF5F5F5,
        labelStyle: const TextStyle(color: JDColors.c222222, fontSize: 21),
        contentPadding: const EdgeInsets.only(left: 75, bottom: 11, right: 30),
        hintText: widget.hintText,
        counterText: '',
        focusedBorder: const UnderlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(54 / 2)),
            borderSide: BorderSide(style: BorderStyle.none)),
        enabledBorder: const UnderlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(54 / 2)),
            borderSide: BorderSide(style: BorderStyle.none)),
      ),
    );

    /// 个别Android机型（华为、vivo）的密码安全键盘不弹出问题（已知小米正常），临时修复方法：https://github.com/flutter/flutter/issues/68571 (issues/61446)
    /// 怀疑是安全键盘与三方输入法之间的切换冲突问题。
    if (Platform.isAndroid) {
      textField = Listener(
        onPointerDown: (e) =>
            FocusScope.of(context).requestFocus(widget.focusNode),
        child: textField,
      );
    }

    Widget? clearButton;

    if (_isShowDelete) {
      clearButton = CommonGestureDetector(
        child: const Padding(
          padding: EdgeInsets.fromLTRB(10, 10, 20, 10),
          child: JDAssetImage(
            'login/login_text_close.png',
            width: 14.0,
            height: 14.0,
          ),
        ),
        onTap: () => widget.controller.text = '',
      );
    }

    return Stack(
      alignment: Alignment.centerLeft,
      children: <Widget>[
        SizedBox(
          height: 54,
          child: textField,
        ),
        // Row(children: [Text('    +86')],)
        const Text('    +86'),
        // const ,
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            /// _isShowDelete参数动态变化，为了不破坏树结构使用Visibility，false时放一个空Widget。
            /// 对于其他参数，为初始配置参数，基本可以确定树结构，就不做空Widget处理。
            Visibility(
              visible: _isShowDelete,
              child: clearButton ?? Gap.empty,
            ),
          ],
        )
      ],
    );
  }
}
